/*
 * @Author: t-xiangqun.li t-xiangqun.li@pcitc.com
 * @Date: 2025-10-28 17:30:19
 * @LastEditors: lixiangqun
 * @LastEditTime: 2025-11-06 10:29:53
 * @FilePath: \electrconVue\src\stores\message.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { defineStore } from "pinia";
import { db } from "../db";
import { MessageProps } from "../types";

export interface MessageStore {
  items: MessageProps[];
}
export const useMessageStore = defineStore("message", {
  state: (): MessageStore => {
    return {
      items: [],
    };
  },
  actions: {
    async fetchMessageByConversationId(conversationId: number) {
      const items = await db.messages.where({ conversationId }).toArray();
      this.items = items;
    },
    async createMessage(data: Omit<MessageProps, "id">) {
      const newId = await db.messages.add(data);
      this.items.push({ ...data, id: newId });
      return newId;
    },
    async updateMessage(messageId: number, updatedData: Partial<MessageProps>) {
      // 更新消息里的AI回答
      await db.messages.update(messageId, updatedData);
      const index = this.items.findIndex((item) => item.id === messageId);
      // 更新消息列表数据
      if (index > -1) {
        this.items[index] = {
          ...this.items[index],
          ...updatedData,
        };
      }

      //   const { messageId, data } = streamData;
      // // 获取到当前的消息，即loading消息的id
      // const currentMessage = this.items.find((item) => item.id === messageId); //await db.messages.where({ id: messageId }).first();
      // // streamContent += data.result;
      // if (currentMessage) {
      //   const updatedMessage = {
      //     // content: currentMessage.content + data.result, //streamContent,
      //     status: (data.finish_reason === "stop"
      //       ? "finished"
      //       : "streaming") as MessageStatus,
      //     updatedAt: new Date().toISOString(),
      //     ...(data.finish_reason !== "stop" && {
      //       content: currentMessage.content + data.result,
      //     }),
      //   };
      //   console.log("streamData", updatedMessage);
      //   console.log("currentMessage", currentMessage);
      //   // 更新消息里的AI回答
      //   await db.messages.update(messageId, updatedMessage);
      //   const index = this.items.findIndex((item) => item.id === messageId);
      //   // 更新消息列表数据
      //   if (index > -1) {
      //     this.items[index] = {
      //       ...this.items[index],
      //       ...updatedMessage,
      //     };
      //   }
      // }
    },
  },
  getters: {
    getLastQuestion: (state) => (conversationId: number) => {
      return state.items.findLast(
        (item) =>
          item.conversationId === conversationId && item.type === "question"
      );
    },
    isMessageLoading: (state) => {
      return !!state.items.some(
        (item) => item.status === "loading" || item.status === "streaming"
      );
    },
  },
});
